package com.breeze.components.socket.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.breeze.components.socket.WebSocket;
import com.breeze.components.socket.WebSocketManager;
import com.breeze.components.socket.WebSocketProperties;
import java.util.Map;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;

/**
 * websocket工具
 *
 * @author breeze
 */
@Slf4j
public class WebSocketUtil {

  public static void broadcastMessage(String message) {
    WebSocketManager manager = SpringUtil.getBean(WebSocketManager.class);
    Map<String, WebSocket> webSocketMap = manager.localWebSocketMap();
    if (CollUtil.isEmpty(webSocketMap)) {
      return;
    }
    webSocketMap.forEach(
        (identifier, webSocket) -> {
          WebSocketSession session = webSocket.getSession();
          if (Objects.nonNull(session) && session.isOpen()) {
            try {
              sendMessage(session, message);
            } catch (Exception e) {
              log.error("推送消息异常：{}", message, e);
            }
          }
        });
  }

  /** 发送消息 */
  public static void sendMessage(WebSocketSession session, String message) {
    try {
      if (sessionNotOpen(session)) {
        return;
      }
      session.sendMessage(new TextMessage(message));
    } catch (Exception e) {
      log.error("推送消息异常：{}", message, e);
    }
  }

  public static WebSocketSession decoratorSession(WebSocketSession session) {
    return new ConcurrentWebSocketSessionDecorator(
        session, WebSocketProperties.getSendTimeLimit(), WebSocketProperties.getBufferSizeLimit());
  }

  private static boolean sessionNotOpen(WebSocketSession session) {
    return Objects.isNull(session) || !session.isOpen();
  }
}
